<template>
  <div class="template-editor">
    <div class="editor-toolbar">
      <el-radio-group v-model="editorMode" size="small" @change="handleEditorModeChange">
        <el-radio-button label="rich">富文本编辑</el-radio-button>
        <el-radio-button label="html">HTML编辑</el-radio-button>
      </el-radio-group>
      
      <div class="toolbar-actions">
        <el-button type="primary" size="small" @click="saveTemplate" icon="Check">保存</el-button>
        <el-button size="small" @click="previewTemplate" icon="View">预览</el-button>
        <el-button size="small" @click="insertVariable" icon="Plus">插入变量</el-button>
      </div>
    </div>
    
    <!-- 富文本编辑器 -->
    <div v-show="editorMode === 'rich'">
      <div ref="richEditor" class="rich-editor"></div>
    </div>
    
    <!-- HTML编辑器 -->
    <div v-show="editorMode === 'html'" class="html-editor-container">
      <el-input
        type="textarea"
        v-model="htmlContent"
        :rows="20"
        placeholder="请输入HTML内容"
        class="html-editor">
      </el-input>
    </div>
    
    <!-- 变量选择对话框 -->
    <el-dialog title="插入模板变量" v-model="variableDialogVisible" width="30%">
      <div class="variable-list">
        <el-table :data="templateVariables" style="width: 100%">
          <el-table-column prop="name" label="变量名称"></el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button link @click="insertVariableToEditor(scope.row)">插入</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="variableDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog title="模板预览" v-model="previewDialogVisible" width="70%" class="preview-dialog">
      <div class="preview-content" v-html="previewContent"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadPreview">下载PDF</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue'
import { getTemplate, updateTemplate, previewTemplate, listTemplateVariables } from '@/api/qep/certificate/template'
import E from 'wangeditor'

const props = defineProps({
  templateId: {
    type: [Number, String],
    required: true
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['saved'])

const editorMode = ref('rich')
const htmlContent = ref('')
const editor = ref(null)
const templateVariables = ref([])
const variableDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const previewContent = ref('')
const templateInfo = ref(null)
const richEditor = ref(null)

onMounted(() => {
  initEditor()
  loadTemplateData()
  loadTemplateVariables()
})

onBeforeUnmount(() => {
  // 销毁编辑器
  if (editor.value) {
    editor.value.destroy()
    editor.value = null
  }
})

const initEditor = () => {
  // 初始化富文本编辑器
  const editorInstance = new E(richEditor.value)

  // 编辑器配置
  editorInstance.config.height = 500
  editorInstance.config.uploadImgServer = import.meta.env.VITE_APP_BASE_API + '/common/upload'
  editorInstance.config.placeholder = '请输入模板内容...'
  
  // 上传图片配置
  editorInstance.config.uploadImgServer = import.meta.env.VITE_APP_BASE_API + '/common/upload'
  editorInstance.config.uploadFileName = 'file'
  editorInstance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2MB
  editorInstance.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif']
  editorInstance.config.uploadImgHeaders = {
    Authorization: 'Bearer ' + localStorage.getItem('token')
  }
  editorInstance.config.uploadImgHooks = {
    customInsert: (insertImgFn, result) => {
      if (result.code === 200) {
        insertImgFn(result.url)
      } else {
        ElMessage.error('图片上传失败')
      }
    }
  }
  
  // 只读模式处理
  if (props.readOnly) {
    editorInstance.config.readOnly = true
  }
  
  // 创建编辑器
  editorInstance.create()
  editor.value = editorInstance
}

const loadTemplateData = async () => {
  try {
    const res = await getTemplate(props.templateId)
    if (res.code === 200) {
      templateInfo.value = res.data
      
      // 设置编辑器内容
      if (templateInfo.value.editorContent) {
        if (templateInfo.value.editorType === 'html') {
          editorMode.value = 'html'
          htmlContent.value = templateInfo.value.editorContent
        } else {
          editorMode.value = 'rich'
          editor.value?.txt.html(templateInfo.value.editorContent)
        }
      } else if (templateInfo.value.content) {
        // 兼容旧数据，如果没有editorContent但有content
        editor.value?.txt.html(templateInfo.value.content)
        htmlContent.value = templateInfo.value.content
      }
    }
  } catch (error) {
    console.error('加载模板数据失败', error)
    ElMessage.error('加载模板数据失败')
  }
}

const loadTemplateVariables = async () => {
  try {
    const res = await listTemplateVariables(props.templateId)
    if (res.code === 200) {
      templateVariables.value = res.data || []
    }
  } catch (error) {
    console.error('加载模板变量失败', error)
  }
}

const handleEditorModeChange = (mode) => {
  if (mode === 'rich') {
    // 从HTML模式切换到富文本模式时，将HTML内容同步到富文本编辑器
    editor.value?.txt.html(htmlContent.value)
  } else {
    // 从富文本模式切换到HTML模式时，将富文本内容同步到HTML编辑器
    htmlContent.value = editor.value ? editor.value.txt.html() : ''
  }
}

const saveTemplate = async () => {
  if (!templateInfo.value) return
  
  const editorContent = editorMode.value === 'rich' 
    ? (editor.value ? editor.value.txt.html() : '') 
    : htmlContent.value
  
  try {
    const templateData = {
      id: props.templateId,
      editorContent: editorContent,
      editorType: editorMode.value
    }
    
    const res = await updateTemplate(templateData)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      emits('saved', templateData)
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存模板失败', error)
    ElMessage.error('保存模板失败')
  }
}

const previewTemplate = async () => {
  try {
    const res = await previewTemplate(props.templateId)
    if (res.code === 200) {
      previewContent.value = res.data
      previewDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '预览失败')
    }
  } catch (error) {
    console.error('预览模板失败', error)
    ElMessage.error('预览模板失败')
  }
}

const insertVariable = () => {
  variableDialogVisible.value = true
}

const insertVariableToEditor = (variable) => {
  // 插入变量格式：${变量名}
  const variableText = '${' + variable.name + '}'
  
  if (editorMode.value === 'rich' && editor.value) {
    editor.value.cmd.do('insertHTML', variableText)
  } else {
    // 在光标位置插入变量，或者在最后插入
    const textarea = document.querySelector('.html-editor textarea')
    if (textarea) {
      const startPos = textarea.selectionStart
      const endPos = textarea.selectionEnd
      const text = htmlContent.value
      htmlContent.value = text.substring(0, startPos) + variableText + text.substring(endPos)
    } else {
      htmlContent.value += variableText
    }
  }
  
  variableDialogVisible.value = false
}

const downloadPreview = () => {
  // 实现下载预览的PDF功能
  // 这里可以向后端请求生成PDF并下载
  ElMessage.info('下载PDF功能开发中...')
}

// 供父组件调用的方法
defineExpose({
  // 获取编辑器内容
  getContent: () => {
    if (editorMode.value === 'rich') {
      return editor.value ? editor.value.txt.html() : ''
    } else {
      return htmlContent.value
    }
  },
  // 设置编辑器内容
  setContent: (html) => {
    if (editorMode.value === 'rich') {
      editor.value?.txt.html(html)
    } else {
      htmlContent.value = html
    }
  }
})
</script>

<style lang="scss" scoped>
.template-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .editor-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    margin-bottom: 10px;
    
    .toolbar-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .rich-editor {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    min-height: 500px;
  }
  
  .html-editor-container {
    height: 100%;
    
    .html-editor {
      height: 100%;
    }
  }
}

.preview-dialog {
  .preview-content {
    max-height: 70vh;
    overflow-y: auto;
    padding: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: white;
  }
}

:deep(.w-e-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

:deep(.w-e-text-container) {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}
</style>
